package pa2.system;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;

public abstract class SystemManagerImpl extends UnicastRemoteObject 
implements SystemManager, Runnable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2810603034693094412L;

	public SystemManagerImpl() throws RemoteException {
		super();
	}

	protected ArrayList<Peer> peers = new ArrayList<Peer>();

	@Override
	public synchronized void registerPeer(Peer peer) throws RemoteException {
		this.peers.add(peer);
		System.out.println("Registered peer "+peer.getName());
		this.peersChanged();
	}

	@Override
	public synchronized void unregisterPeer(Peer peer) throws RemoteException {
		//TODO call this method if someone notices a peer disconnects 
		//(either by peer itself or through exception)
		this.peers.remove(peer);
		System.out.println("Deregistered peer "+peer.getName());
		this.peersChanged();
	}


	@Override
	public void run() {
		String port = Integer.toString(Registry.REGISTRY_PORT);

		try {
			Registry registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
			registry.rebind(
					"rmi://localhost:" + port + "/" + SystemManager.SERVICENAME,
					this);
			System.out.println("Bound SystemManager in local registry.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected abstract void peersChanged() throws RemoteException;

}
